#include "SocketTcp.h"
#include "Tool.h"


CSocketTcp::CSocketTcp()
{
    SocketValue = -1;
}


CSocketTcp::~CSocketTcp()
{
    
}


int CSocketTcp::InitSocket()
{
    WSAData wasData;
    int iRet = WSAStartup(MAKEWORD(2, 2), &wasData);
    if (iRet != 0)
    {
        CTool::ReportError("CSocketTcp::InitSocket()");
        return iRet;
    }
    return 0;
}


int CSocketTcp::CreateSocket()
{
    SocketValue = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (SocketValue < 0)
    {
        CTool::ReportError("CSocketTcp::CreateSocket()");
        return SocketValue;
    }
    return 0;
}


int CSocketTcp::Listen(int iValue)
{
    int iRet = listen(SocketValue, iValue);
    if (iRet < 0)
    {
        CTool::ReportError("CSocketTcp::Listen(int iValue)");
    }

    return iRet;
}


int CSocketTcp::Accept(CSocketTcp& ClientSocket)
{
    int iLenthSockaddr_in = ClientSocket.IpAdress.GetSize();
    int iClientSocket = accept(SocketValue, (sockaddr *)&ClientSocket.IpAdress, &iLenthSockaddr_in);
    if (iClientSocket < 0)
    {
        CTool::ReportError("CSocketTcp::Accept(CIpAddress& SeverIpAddress)");
        return iClientSocket;
    }
    ClientSocket.SocketValue = iClientSocket;
    return iClientSocket;
}


int CSocketTcp::Bind(CIpAddress& SeverIpAdress)
{
    int iRet = bind(SocketValue, SeverIpAdress.GetIpAdressStrut(), SeverIpAdress.GetSize());
    if (iRet != 0)
    {
        CTool::ReportError("CSocketTcp::Bind");
    }
    return iRet;
}


int CSocketTcp::Send(char *szBuffer, int iLenth)
{
    uint32_t t32Byte = send(SocketValue, szBuffer, iLenth, 0);
    if (t32Byte <= 0)
    {
        CTool::ReportError("CSocketTcp::Send");
    }
    return t32Byte;
}


int CSocketTcp::Recv(char *szBuffer, int iLenth)
{
    uint32_t t32Byte = recv(SocketValue, szBuffer, iLenth, 0);
    if (t32Byte <= 0)
    {
        CTool::ReportError("CSocketTcp::Send");
    }
    return t32Byte;
}


int CSocketTcp::Connect(CIpAddress& SeverIpAdress)
{
    int iRet = connect(SocketValue, SeverIpAdress.GetIpAdressStrut(), SeverIpAdress.GetSize());
    if (iRet < 0)
    {
        CTool::ReportError("CSocketTcp::Connect()");
    }
    return iRet;
}



int CSocketTcp::GetSocketValue()
{
    return SocketValue;
}


CIpAddress& CSocketTcp::GetIpAdress()
{
    return IpAdress;
}